import Dep from "./Dep.js";
import { parsePath } from "./utils.js";
var uid = 0;
export default class Watcher {
    constructor(target, expression, callback) {
        this.id = uid++;
        this.target = target;
        this.getter = parsePath(expression);
        this.callback = callback;
        this.value = this.get();
    }
    update() {
        this.run();
    }
    get() {
        // 进入依赖收集的阶段
        Dep['target'] = this;
        const obj = this.target;
        let value;
        try {
            value = this.getter(obj);
        } finally {
            Dep['target'] = null;
        }
        return value;
    }
    run() {
        this.getAndInoke(this.callback);
    }
    getAndInoke(callback) {
        const value = this.get();
        if (value != this.value || typeof value == 'object') {
            const oldValue = this.value;
            this.value = value;
            callback.call(this.target, value, oldValue);
        }
    }
}